package com.next

import java.text.SimpleDateFormat

class Contract
{
    String serialNumber
    String subject

    ContractType type
    ContractStatus status

    String externalId

    User createBy
    User modifyBy
    User user
    Double amount = 0

    Date startTime
    Date endTime

    Date createdDate = new Date()
    Date modifiedDate = new Date()

    static belongsTo = [account: Account]

    static constraints = {
        serialNumber maxSize: 128, nullable: true, blank: true
        externalId maxSize: 32, blank: true, nullable: true
        account blank: true, nullable: true

        createBy blank: true, nullable: true
        modifyBy blank: true, nullable: true
        user blank: true, nullable: true

        createdDate blank: true, nullable: true
        modifiedDate blank: true, nullable: true

        endTime blank: true, nullable: true

        subject maxSize: 128, blank: true, nullable: true

        startTime blank: true, nullable: true

        amount blank: false, nullable: true
    }

    static mapping = {
        sort 'modifiedDate': 'desc'
    }

    String toString()
    {
        "${subject} - ${serialNumber}"
    }

    def springSecurityService

    def beforeInsert()
    {
        def username = springSecurityService?.getPrincipal()?.username
        createBy = User.findByUsername(username)
        if (!user)
        {
            user = createBy
        }
    }

    def afterInsert()
    {
        if (!serialNumber)
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd")
            def s = sdf.format(Calendar.getInstance().getTime())
            def count = String.format("%06d", Contract.count() + 1)
            serialNumber = "${s}${count}"
        }
        def flexFieldCategories = FlexFieldCategory.findAllByObjectType('Contract')
        flexFieldCategories?.each {
            if (it?.condition)
            {
                def result = false
                try
                {
                    def shell = new GroovyShell()
                    def closure = shell.evaluate(it?.condition?.script)
                    result = closure(this)
                }
                catch (Exception e)
                {
                    log.error e
                }
                if (result)
                {
                    initFlexField(it)
                }
            }
            else
            {
                initFlexField(it)
            }
        }

    }

    def initFlexField(FlexFieldCategory flexFieldCategory)
    {
        def fields = FlexField.findAllByCategory(flexFieldCategory)
        fields?.each {
            def field = new FlexFieldInstance(category: flexFieldCategory, field: it, contract: this)
            field.save()
        }
    }

    def beforeUpdate()
    {
        modifiedDate = new Date()
        def username = springSecurityService?.getPrincipal()?.username
        modifyBy = User.findByUsername(username)
    }
}
